package io.terminus.lego.shinda.web.security.special_user.filter

import io.terminus.lego.shinda.web.security.phone.token.SpecialUserLoginAuthenticationToken
import org.springframework.http.HttpMethod
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter
import org.springframework.security.web.util.matcher.AntPathRequestMatcher
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *特殊账户登录
 * @author wangmeng
 * @date 2018/4/28
 */

class SpecialUserAuthenticationProcessingFilter : AbstractAuthenticationProcessingFilter {
    var PARAMTER_KEY_USERNAME = "username"
    var PARAMTER_KEY_PASSWORD = "password"
    var PARAMTER_KEY_USERTYPE = "user_type"

    /**
     * 也可以将路径合并为一个，根据不同的参数区分生成哪一种认证token。不过不利于维护。
     */
    constructor() : super(AntPathRequestMatcher("/login-special", HttpMethod.POST.name))


    override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication {
        var username = request.getParameter(PARAMTER_KEY_USERNAME)
        var password = request.getParameter(PARAMTER_KEY_PASSWORD)
        var userType = request.getParameter(PARAMTER_KEY_USERTYPE)
        if (username.isNullOrEmpty()) {
            username = ""
        }
        if (password.isNullOrEmpty()) {
            password = ""
        }
        if (userType.isNullOrEmpty()) {
            userType = ""
        }
        username = username.trim()
        val authRequest = SpecialUserLoginAuthenticationToken(username, password, userType)
        // Allow subclasses to set the "details" property
        setDetails(request, authRequest)

        return this.authenticationManager.authenticate(authRequest)
    }

    private fun setDetails(request: HttpServletRequest, authRequest: SpecialUserLoginAuthenticationToken) {
        authRequest.details = authenticationDetailsSource.buildDetails(request)
    }

}